//
//  QSNetworkTool.m
//  SinaWeiBo
//
//  Created by apple on 16/5/30.
//  Copyright © 2016年 song. All rights reserved.
//

#import "QSNetworkTool.h"

@implementation QSNetworkTool
/**
 *  创建单例
 */
+ (instancetype)shareNetworkInstance
{
    // 初始化单例对象
    static QSNetworkTool *instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[QSNetworkTool alloc] init];
        instance.afManager = [[AFHTTPSessionManager alloc] init];
        
        instance.requestType = QSRequestTypeHTTP;
        instance.responseType = QSResponseTypeJson;
        
        // 设置超时时间
        [instance.afManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        instance.afManager.requestSerializer.timeoutInterval = 10.f;
        [instance.afManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    });
    
    return instance;
}

/**
 *  post
 */
- (void)postWithURL:(NSString *)url Parameter:(NSMutableDictionary *)param Finish:(HttpResponseSuccessBlock)completeBlock Error:(HttpResponseErrorBlock)errorBlock
{
    if (self.networkStatus == QSNetworkStatusNone) {
        [QSSV_HUDTool sv_showFailHUDWithMessage:@"您的网络不给力，请检查网络后重试！"];
        return;
    }
    
    NSString *postUrl = [NSString string];
    if ([url hasPrefix:@"http"] || [url hasPrefix:@"https"]) {
        postUrl = url;
    } else {
        postUrl = [kInterfaceAddress stringByAppendingString:url];
    }
    QSLog(@"请求url = %@  参数 = %@", postUrl, param);
    
    switch (self.requestType) {
        case QSRequestTypeJson:
            self.afManager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
            
        case QSRequestTypeHTTP:
            self.afManager.requestSerializer = [AFHTTPRequestSerializer serializer];
            break;
    }
    
    switch (self.responseType) {
        case QSResponseTypeJson:
            self.afManager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
            
        case QSResponseTypeHTTP:
            self.afManager.responseSerializer = [AFHTTPResponseSerializer  serializer];
            break;
    }
    
    [self.afManager POST:postUrl parameters:param progress:^(NSProgress *  uploadProgress) {
    } success:^(NSURLSessionDataTask *  task, id  responseObject) {
        completeBlock(responseObject);
    } failure:^(NSURLSessionDataTask *  task, NSError *  error) {
        QSLog(@"=====请求失败=====%@",error);
        [QSSV_HUDTool sv_showFailHUDWithMessage:@"您的网络不给力，请检查网络后重试！"];
        errorBlock(task , error,@"");
    }];
}

/**
 *  get
 */
- (void)getWithURL:(NSString*)url Parameter:(NSMutableDictionary *)param Finish:(HttpResponseSuccessBlock)completeBlock Error:(HttpResponseErrorBlock)errorBlock
{
    if (self.networkStatus == QSNetworkStatusNone) {
        [QSSV_HUDTool sv_showFailHUDWithMessage:@"您的网络不给力，请检查网络后重试！"];
        return;
    }
    
    NSString *postUrl = [NSString string];
    if ([url hasPrefix:@"http"] || [url hasPrefix:@"https"]) {
        postUrl = url;
    } else {
        postUrl = [kInterfaceAddress stringByAppendingString:url];
    }
    QSLog(@"请求url = %@  参数 = %@", postUrl, param);
    
    switch (self.requestType) {
        case QSRequestTypeJson:
            self.afManager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
            
        case QSRequestTypeHTTP:
            self.afManager.requestSerializer = [AFHTTPRequestSerializer serializer];
            break;
    }
    
    switch (self.responseType) {
        case QSResponseTypeJson:
            self.afManager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
            
        case QSResponseTypeHTTP:
            self.afManager.responseSerializer = [AFHTTPResponseSerializer  serializer];
            break;
    }

    [self.afManager GET:postUrl parameters:param progress:^(NSProgress *uploadProgress) {
    } success:^(NSURLSessionDataTask *task, id  responseObject) {
        completeBlock(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        QSLog(@"=====请求失败=====%@",error);
        [QSSV_HUDTool sv_showFailHUDWithMessage:@"您的网络不给力，请检查网络后重试！"];
        errorBlock(task , error,@"");
    }];
}

/**
 *  上传文件(返回数据做Json解析)
 */
- (void)uploadDataWithUrl:(NSString *)url Parameter:(NSDictionary *)param updata:(HttpUploadDataBlock)uploadDataBlock Finish:(HttpResponseSuccessBlock)completeBlock Error:(HttpResponseErrorBlock)errorBlock
{
    if (self.networkStatus == QSNetworkStatusNone) {
        [QSSV_HUDTool sv_showFailHUDWithMessage:@"您的网络不给力，请检查网络后重试！"];
        return;
    }
    
    NSString *postUrl = [NSString string];
    if ([url hasPrefix:@"http"] || [url hasPrefix:@"https"]) {
        postUrl = url;
    } else {
        postUrl = [kInterfaceAddress stringByAppendingString:url];
    }
    QSLog(@"请求url = %@  参数 = %@", postUrl, param);
    
    switch (self.requestType) {
        case QSRequestTypeJson:
            self.afManager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
            
        case QSRequestTypeHTTP:
            self.afManager.requestSerializer = [AFHTTPRequestSerializer serializer];
            break;
    }
    
    switch (self.responseType) {
        case QSResponseTypeJson:
            self.afManager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
            
        case QSResponseTypeHTTP:
            self.afManager.responseSerializer = [AFHTTPResponseSerializer  serializer];
            break;
    }
    
    [self.afManager POST:postUrl parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        uploadDataBlock(formData);
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completeBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        QSLog(@"=====请求失败=====%@",error);
        [QSSV_HUDTool sv_showFailHUDWithMessage:@"您的网络不给力，请检查网络后重试！"];
        errorBlock(task, error, @"");
    }];
}

/**
 *  重写networkStatus的get方法
 */
- (NSInteger)networkStatus
{
    __block QSNetworkStatus netStatus;
    
    // 创建NetworkReachabilityManager管理者
    AFNetworkReachabilityManager *netReManager = [AFNetworkReachabilityManager sharedManager];
    [netReManager startMonitoring];  //开始监听
    [netReManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        /*
         AFNetworkReachabilityStatusUnknown          = -1,
         AFNetworkReachabilityStatusNotReachable     = 0,
         AFNetworkReachabilityStatusReachableViaWWAN = 1,
         AFNetworkReachabilityStatusReachableViaWiFi = 2,
         */
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                netStatus = QSNetworkStatusNone;
                break;
            case AFNetworkReachabilityStatusNotReachable:
                netStatus = QSNetworkStatusNone;
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                netStatus = QSNetworkStatusPhone;
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                netStatus = QSNetworkStatusWifi;
                break;
            default:
                break;
        }
    }];
    
    // 开启网络监听
    [netReManager startMonitoring];
    return netStatus;
}

/**
 *  取消当前请求队列的所有请求
 */
- (void)cancelAllOperations
{
    [self.afManager.operationQueue cancelAllOperations];
}
@end
